#include "dataBase.h"

int initDatabase(MYSQL** mysql,dataBase_t database) {
    *mysql = mysql_init(NULL);
    MYSQL* ret = mysql_real_connect(*mysql,database.host,database.user,database.passwd,database.db,0,NULL,0);
    // MYSQL* ret = mysql_real_connect(mysql,"localhost","root","123","test",0,NULL,0);
    if(ret == NULL) {
        fprintf(stderr,"%s:%s\n","mysql_real_connect",mysql_error(*mysql));
        return -1;
    }
    return 0;
}


int initGlobalDataBase(const dataBase_t database) {
    MYSQL *mysql = mysql_init(NULL);
    MYSQL* ret = mysql_real_connect(mysql,database.host,database.user,database.passwd,database.db,0,NULL,0);
    // MYSQL* ret = mysql_real_connect(mysql,"localhost","root","123","test",0,NULL,0);
    if(ret == NULL) {
        fprintf(stderr,"%s:%s\n","mysql_real_connect",mysql_error(mysql));
        return -1;
    }

    // 创建user表
    if(isExistTable(mysql,database,"User") != 0) {
        char create_table_sql[] = "create table User( \
                            user_id int not null auto_increment, \
                            user_name varchar(256) not null, \
                            user_pwd varchar(512) not null, \
                            user_salt varchar(512) not null, \
                            is_deleted boolean not null default true, \
                            primary key(user_id));";
        int ret = mysql_query(mysql,create_table_sql);
        if(ret == -1) {
            fprintf(stderr,"%s\n",mysql_error(mysql));
            closeDataBase(&mysql);
            return -1;
        }
    }

    // 创建FileSystem表
    if(isExistTable(mysql,database,"FileSystem") != 0) {
        char create_table_sql[] = "create table FileSystem( \
                                file_id int not null auto_increment, \
                                file_name varchar(256) not null, \
                                user_id int not null, \
                                file_category char(1) not null, \
                                file_hash varchar(65), \
                                file_size bigint, \
                                last_active bigint, \
                                file_path varchar(512), \
                                parent_id int not null, \
                                completed_file boolean default true, \
                                is_deleted boolean not null default true, \
                                primary key(file_id));";
        int ret = mysql_query(mysql,create_table_sql);
        if(ret == -1) {
            fprintf(stderr,"%s\n",mysql_error(mysql));
            closeDataBase(&mysql);
            return -1;
        }
    }
    closeDataBase(&mysql);
    return 0;
}
int closeDataBase(MYSQL** mysql) {
    mysql_close(*mysql);
    return 0;
}

int isExistTable(MYSQL* mysql,dataBase_t database,const char* table_name) {
    char query[] = "show tables;";
    int query_ret = mysql_query(mysql,query);
    if(query_ret != 0) {
        printf("Error: %s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES* res = mysql_store_result(mysql);
    int size = mysql_num_rows(res);
    MYSQL_ROW row;
    while((row = mysql_fetch_row(res)) != NULL) {
        for(int i = 0;i < size;++i) {
            if(strcmp(row[i],table_name) == 0) {
                return 0;
            }
        }
    }
    return -1;
}

int insertDataElem(MYSQL* mysql,const char* data_table_name,const char* data_elem) {
    char query[1024] = {0};
    sprintf(query,"insert into %s values %s;",data_table_name,data_elem);
    int query_ret = mysql_query(mysql,query);
    if(query_ret == -1) {
        fprintf(stderr,"%s:%s\n","insertDataElem",mysql_error(mysql));
        return -1;
    }
    return 0;
}

int insertDirElem(MYSQL* mysql,const char* dir_name,const int user_id,const long long file_size,const char* file_path,const int parent_id) {
    char query[1024] = {0};
    time_t active_time = time(NULL);
    sprintf(query,"insert into FileSystem values (default,'%s',%d,'d',NULL,%lld,%ld,'%s',%d,default,default)",
        dir_name,user_id,file_size,active_time,file_path,parent_id);
    int query_ret = mysql_query(mysql,query);
    printf("query : %s\n",query);
    if(query_ret != 0) {
        fprintf(stderr,"%s:%s\n","insertDataElem",mysql_error(mysql));
        return -1;
    }
    return 0;
}
int insertFileElem(MYSQL* mysql,const char* file_name,const int user_id,const char* hash,const long long file_size,const char* file_path,const int parent_id) {
    char query[1024] = {0};
    time_t active_time = time(NULL);

    sprintf(query,"insert into FileSystem values (default,'%s',%d,'f','%s',%lld,%ld,'%s',%d,default,default)",
        file_name,user_id,hash,file_size,active_time,file_path,parent_id);
    int query_ret = mysql_query(mysql,query);
    if(query_ret == -1) {
        fprintf(stderr,"%s:%s\n","insertDataElem",mysql_error(mysql));
        return -1;
    }
    return 0;
}

int createUserDir(MYSQL* mysql,const char* user_name) {
    // 检查
    char query[1024] = {0};
    sprintf(query,"select * from FileSystem \
        where file_name = '%s' and file_path = '/' and is_deleted;",user_name);
    int query_ret = mysql_query(mysql,query);
    if(query_ret != 0) {
        fprintf(stderr,"%s:%s\n","createUserDir",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES* res = mysql_store_result(mysql);
    MYSQL_ROW row;
    if(mysql_num_rows(res) > 0) {
        // 已存在
        printf("已存在该目录\n");
        return -1;
    }
    mysql_free_result(res);
    memset(query,0,sizeof(query));
    sprintf(query,"select user_id from User where user_name = '%s';",user_name);
    query_ret = mysql_query(mysql,query);
    if(query_ret != 0) {
        fprintf(stderr,"%s:%s\n","createUserDir",mysql_error(mysql));
        return -1;
    }
    res = mysql_store_result(mysql);
    row = mysql_fetch_row(res);
    int user_id = atoi(row[0]);
    insertDirElem(mysql,user_name,user_id,0,"/",-1);
    return 0;
}

int getUserRootDirId(MYSQL* mysql,const int user_id) {
    char query[1024] = {0};
    MYSQL_RES* res;
    MYSQL_ROW row;
    sprintf(query,"select file_id from FileSystem \
        where user_id = %d and parent_id = -1 and file_category = 'd';",user_id);
    int query_ret = mysql_query(mysql,query);
    if(query_ret != 0) {
        fprintf(stderr,"%s:%s\n","getUserRootDirId",mysql_error(mysql));
        return -1;
    }
    res = mysql_store_result(mysql);
    int size = mysql_num_rows(res);
    printf("size = %d\n",size);
    if(size == 1) {
        // 存在
        row = mysql_fetch_row(res);
        int user_root_dir_id = atoi(row[0]);
        printf("user_root_dir_id = %d\n",user_root_dir_id);
        return user_root_dir_id;
    }
    return -1;
}

int selectField(MYSQL* mysql,const char* table_name,const char* field_name,const char* where_query,char **result) {
    MYSQL_RES* res;
    MYSQL_ROW row;
    char query[1024] = {0};
    sprintf(query,"select %s from %s where %s;",field_name,table_name,where_query);
    int query_ret = mysql_query(mysql,query);
    if(query_ret != 0) {
        fprintf(stderr,"%s:%s\n","selectField",mysql_error(mysql));
        return -1;
    }
    res = mysql_store_result(mysql);
    row = mysql_fetch_row(res);
    memcpy(*result,row[0],strlen(row[0]));
    return 0;
}

int getFilePathByFileID(MYSQL* mysql,const int file_id,char** current_file_path) {
    MYSQL_RES* res;
    MYSQL_ROW row;
    char query[1024] = {0};
    sprintf(query,"select file_path from FileSystem where file_id = %d;",file_id);
    int query_ret = mysql_query(mysql,query);
    if(query_ret != 0) {
        fprintf(stderr,"%s:%s\n","getFilePathByFileID",mysql_error(mysql));
        return -1;
    }
    res = mysql_store_result(mysql);
    row = mysql_fetch_row(res);
    if(row != NULL) {
        memcpy(*current_file_path,row[0],strlen(row[0]));
        return 0;
    }
    return -1;
}

